import logging
import time
import unittest

import selenium.webdriver.support.expected_conditions as EC
from selenium.webdriver.common.action_chains import ActionChains
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions
# import pyperclip
# from dateutil.relativedelta import relativedelta
# from selenium.webdriver.support import expected_conditions
from selenium.webdriver.support.wait import WebDriverWait


class Action(unittest.TestCase):

    # def __init__(self, base_url,selenium_driver):
    def __init__(self, base_url):  # ,selenium_driver

        self.base_url = base_url
        self._driver = Action._driver
        # self.pagetilte = pagetilte
        # self.driver = selenium_driver

    # def _open(self,url,pagetile):
    #打开浏览器
    def _open(self, url):
        self._driver.get(url)
        self._driver.get(url)
        self._driver.implicitly_wait(10)

    #查找元素隐式等待
    def find_element(self, *loc, visiable=False, waittime=10):
        if waittime != 10:
            self._driver.implicitly_wait(waittime)
        try:
            if visiable:
                WebDriverWait(self._driver, waittime).until(lambda driver: driver.find_element(*loc).is_displayed())
            else:
                WebDriverWait(self._driver, waittime).until(lambda driver: driver.find_element(*loc))
                WebDriverWait(self._driver, waittime).until(EC.visibility_of_element_located(loc))
            return self._driver.find_element(*loc)
        except:
            pass
        finally:
            if waittime != 10:
                self._driver.implicitly_wait(10)
   #直接查找元素（隐式等待）
    def find_elementNoWait(self, loc):
        self._driver.implicitly_wait(0)
        try:
            return self._driver.find_element(*loc)
        except:
            pass
        self._driver.implicitly_wait(6)
    #查找元素
    def find_elements(self, *loc):
        try:
            return self._driver.find_elements(*loc)
        except:
            pass
   #元素存在判断
    def isElementExist(self, *loc):
        flag = True
        ele = self.find_elementNoWait(loc)
        if ele == None:
            flag = False
        return flag
    #元素是否展示
    def Element_displayed(self, *loc):
        try:
            return (self.find_elementNoWait(loc).is_displayed())
        except:
            return False
    #元素可编辑判断
    def isElementEditable(self, loc):
        if isinstance(loc, tuple):
            ele = self.find_element(*loc)
        else:
            ele = loc
        if ele.tag_name == 'textarea':
            status = not ele.get_attribute("readonly")
        else:
            status = not ele.get_attribute("disabled")
        return status
   #输入文本框
    def Input_text(self, text, loc):
        self.execute_keyboardclear(loc)
        self.find_element(*loc).send_keys(text)
    #打开浏览器
    def open(self):
        self._open(self.base_url, self.pagetitle)
    #当前页面
    def on_page(self, pagetitle):
        return pagetitle in self._driver.title
    #传值
    def send_keys(self, loc, vaule, clear_first=True, click_first=True):  # For admin page to add OM
        try:
            ele = self.find_element(*loc)
            if click_first:
                self.js_click(ele)
            if clear_first:
                self.execute_keyboardclear(ele)
            ele.send_keys(vaule)
        except AttributeError:
            logging.info(u"%s This page can not find this  %s element" % (self, loc))

   #等待元素消失
    def wait_element_disappear(self, loc):
        try:
            time.sleep(0.5)
            while self._driver.find_element(*loc):
                WebDriverWait(self._driver, 10, 0.5).until_not(
                    EC.visibility_of_element_located(loc))
                break
        except Exception as e:
            pass
   #等待加载结束
    def wait_loadingmask_disappear(self, waittime=0.5):
        try:
            time.sleep(waittime)
            while self._driver.find_element(*(By.CLASS_NAME, "loading-mask")):
                WebDriverWait(self._driver, 5, 0.5).until_not(
                    EC.visibility_of_element_located((By.CLASS_NAME, "loading-mask")))
                break
        except Exception as e:
            pass
   #刷新当前页
    def refresh_window(self):
        self._driver.refresh()
   #点击元素
    def smart_click(self, *element_loc, isWait=False):
        for i in range(1):
            try:
                self._driver.find_element(*element_loc).click()
                break
            except Exception as e:
                time.sleep(3)
                if i >= 1:
                    raise e
        if isWait:
            self.wait_loadingmask_disappear()
   #左击
    def left_click(self, element):
        ActionChains(self._driver).click(element).perform()
   #右击
    def right_click(self,element):
        ActionChains(self._driver).context_click(element).perform()

   #js点击
    def js_click(self, element, isWait=0):
        if isinstance(element, tuple):
            element = self.find_element(*element)
        self._driver.execute_script("arguments[0].click()", element)
        if isWait:
            self.wait_loadingmask_disappear(1)

    def switch_window(self):
        newHandle = self._driver.window_handles[-1]
        self._driver.switch_to.window(newHandle)

    #滚动至元素可见
    def scroll_into_view(self, element):
        self._driver.execute_script("arguments[0].scrollIntoView()", element)

    def wait_for_element(self, *locator, timeout=10):
        """等待元素出现"""
        return WebDriverWait(self._driver, timeout).until(
            expected_conditions.presence_of_element_located(locator)
        )
    def wait_for_element_clickable(self, *locator, timeout=10):
        """等待元素可见"""
        return WebDriverWait(self._driver, timeout).until(
            expected_conditions.element_to_be_clickable(locator)
        )

    def wait_for_element_visible(self, *locator, timeout=10):
        """等待元素可点击"""
        return WebDriverWait(self._driver, timeout).until(
            expected_conditions.visibility_of_element_located(locator)
        )
